package tcnplanner;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
import javax.persistence.criteria.CriteriaQuery;

public class ReservationService {

    EntityManager em = null;

    public ReservationService(EntityManager em) {
        this.em = em;
    }

    public int count() {
        return this.findAll().size();
    }

    public boolean create(Reservation r) {
        em.persist(r);
        return true;
    }

    public boolean edit(Reservation r) {
        em.merge(r);
        return true;
    }

    public Reservation find(int id) {
        Query q = em.createNamedQuery("Reservation.findById", Item.class);
        q.setParameter("id", id);
        if (q.getResultList().isEmpty()) {
            return null;
        } else {
            return (Reservation) q.getSingleResult();
        }
    }

    public ArrayList<Reservation> findAll() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Reservation.class));
        return new ArrayList(em.createQuery(cq).getResultList());
    }

    /*public Reservation findById(int id) {
    return reservations.get(id);
    }*/
    public void remove(Reservation r) {
        em.remove(r);
    }

    public void removeAll() {
        //reservations.clear();
    }

    public boolean updateReservation(Reservation r) {
        try {
            em.getTransaction().begin();
            em.flush();
            em.getTransaction().commit();
            return true;
        } catch(Exception ex){
            return false;
        }
    }
}
